package com.umeox.watch.moto.gallery.ui;


import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.common.utils.FileUtils;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.moto.watch.themes.dialog.ActionOptionsDialog;
import com.umeox.moto.watch.themes.util.UToast;
import com.umeox.moto.watch.themes.widget.ItemDecoration;
import com.umeox.watch.moto.gallery.R;
import com.umeox.watch.moto.gallery.adapter.AlbumListAdapter;
import com.umeox.watch.moto.gallery.bean.Photo;
import com.umeox.watch.moto.gallery.utils.NetworkUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;


public class AlbumListActivity extends ThemeAppCompatActivity implements AlbumListAdapter.ItemClickListener, AlbumListAdapter.ItemLongClickListener, View.OnClickListener, ActionOptionsDialog.OnClickListener {

    private static final String TAG = AlbumListActivity.class.getSimpleName();
    private static final int REQUEST_CODE = 101;
    private static final int SCAN_COMPLETE = 0x110;
    private static final int DELETE_COMPLETE = 0x111;
    private static final int NO_NETWORK = 0x112;

    private static final int[] RES_ID_DESTS = {
           R.string.str_upload,
            R.string.str_delete
    };
    private static final int[] RES_ID_ICONS = {
            R.drawable.gallery_upload_icon,
            R.drawable.gallery_delete_icon,
    };

    private ImageView mOptionIv;
    ArrayList<Photo> mPhotos = new ArrayList<>();

    private AlbumListAdapter mAlbumListAdapter;
    private Mode MODE = Mode.MODE_NORMAL;
    final String TARGET_DIRECTORY = FileUtils.getAppGalleryCache();
    private boolean isBatch = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_album_list);
        initView();
        getAllPhotos();
        registerObserver();
    }


    private void initView() {
        mOptionIv = findViewById(R.id.iv_options_home);

        RecyclerView albumRv = findViewById(R.id.rv_album_list);
        mOptionIv.setOnClickListener(this);
        mAlbumListAdapter = new AlbumListAdapter(getApplicationContext(), this, this);

        albumRv.setHasFixedSize(true);
        albumRv.setAdapter(mAlbumListAdapter);
        albumRv.addItemDecoration(new ItemDecoration(0,4));
    }


    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case SCAN_COMPLETE:
                    mAlbumListAdapter.setDatas(mPhotos);
                    if (mPhotos.isEmpty()) {
                        return false;
                    }
                    break;
                case DELETE_COMPLETE:
                    isBatch = false;
                    MODE = Mode.MODE_NORMAL;
                    mAlbumListAdapter.setDatas(mPhotos);
                    mAlbumListAdapter.notifyDataSetChanged();
                    showOrHideOption(View.GONE);
                    break;
                case NO_NETWORK:
                    UToast.showCustomToast(AlbumListActivity.this, R.string.sim_state_unknown, 2000);
                    break;
            }
            return false;
        }
    });


    @Override
    public void onOption1Click() {
        if (mAlbumListAdapter.getPhotosSelected().isEmpty()) {
            return;
        }

        if (!NetworkUtils.isNetworkAvailable(this)) {
            mHandler.sendEmptyMessage(NO_NETWORK);
            return;
        }
        if (mOptionIv.getVisibility() == View.VISIBLE) {
            showOrHideOption(View.GONE);
            MODE = Mode.MODE_NORMAL;

        }
        //启动上传Activity
        List<String> mSelectedImage = mAlbumListAdapter.getPhotoPaths();
        Intent intent = new Intent(AlbumListActivity.this, UploadActivity.class);
        intent.putStringArrayListExtra("list", (ArrayList<String>) mSelectedImage);
        startActivity(intent);
        mAlbumListAdapter.resetData();
    }

    @Override
    public void onOption2Click() {
        if (mAlbumListAdapter.getPhotosSelected().isEmpty()) {
            return;
        }
        isBatch = true;
        Intent intent = new Intent(AlbumListActivity.this, ConfirmDeleteActivity.class);
        intent.putStringArrayListExtra("list", mAlbumListAdapter.getPhotoPaths());
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    public void onOption3Click() {

    }

    @Override
    public void onOption4Click() {

    }

    public enum Mode {
        MODE_SELECT, MODE_NORMAL
    }


    private void getAllPhotos() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
            return;
        }

        Executors.newSingleThreadExecutor().execute(() -> {
            // 只查询jpeg和png的图片
            Cursor mCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,
                    MediaStore.Images.Media.MIME_TYPE + "=? or "
                            + MediaStore.Images.Media.MIME_TYPE + "=?",
                    new String[]{"image/jpeg", "image/png"},
                    MediaStore.Images.Media.DATE_MODIFIED + " desc");
            if (mCursor != null) {
                Logger.e("TAG", "count:" + mCursor.getCount());
                mPhotos.clear();
                while (mCursor.moveToNext()) {
                    String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    File file = new File(path);
                    final String absolutePath = file.getAbsolutePath();
                    if (absolutePath.startsWith(TARGET_DIRECTORY + File.separator + "IMG_")) {
                        Photo photo = new Photo();
                        photo.setPath(path);
                        mPhotos.add(photo);
                    }
                }
                mCursor.close();

                // 通知Handler扫描图片完成
                mHandler.sendEmptyMessage(SCAN_COMPLETE);//0x110
            }
        });
    }

    private void registerObserver() {
        getContentResolver().registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, mScanImageObserver);
    }


    @Override
    public boolean onItemLongClick(int position) {

        if (MODE == Mode.MODE_NORMAL) {
            MODE = Mode.MODE_SELECT;
            //震动300毫秒
            Vibrator vibrator = (Vibrator) AlbumListActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
            vibrator.vibrate(100);
            showOrHideOption(View.VISIBLE);
            mAlbumListAdapter.setSelectMode(true);
            mAlbumListAdapter.addOrRemoveSelected(position);
            mAlbumListAdapter.notifyDataSetChanged();

        }
        return true;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_options_home:
                ActionOptionsDialog dialog = new ActionOptionsDialog(this, RES_ID_DESTS, RES_ID_ICONS,this);
                dialog.setOnClickListener(this);
                dialog.show();
                break;
            default:
                //ignore
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (mOptionIv.getVisibility() == View.VISIBLE) {
            showOrHideOption(View.GONE);
            mAlbumListAdapter.resetData();
            MODE = Mode.MODE_NORMAL;
        } else {
            finish();
        }
    }


    @Override
    protected void onDestroy() {
        getContentResolver().unregisterContentObserver(mScanImageObserver);
        super.onDestroy();
    }

    private final ContentObserver mScanImageObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            if (!isBatch) {
                getAllPhotos();
            }
        }
    };

    @Override
    public void onItemClicked(int position) {
        switch (MODE) {
            case MODE_NORMAL:
                //跳转到单张浏览界面
                Logger.e("TAG", "MODE_NORMAL item " + position + " clicked");
                Intent intent = new Intent(AlbumListActivity.this, BigPhotoActivity.class);
                intent.putExtra(BigPhotoActivity.POSITION, position);
                ArrayList<String> photoPaths = new ArrayList<>();
                for (Photo photo : mPhotos) {
                    photoPaths.add(photo.getPath());
                }
                intent.putStringArrayListExtra(BigPhotoActivity.PHOTO_LIST, photoPaths);
                startActivity(intent);
                break;
            case MODE_SELECT:
                mAlbumListAdapter.addOrRemoveSelected(position);
                mAlbumListAdapter.notifyDataSetChanged();

                break;
        }
    }

    /**
     * 收到已选中照片为空的通知
     */
    @Override
    public void notifyPhotoSelectedIsEmpty() {
        MODE = Mode.MODE_NORMAL;
        mAlbumListAdapter.setSelectMode(false);
        showOrHideOption(View.GONE);
    }

    /**
     * 隐藏或显示底部控件
     *
     * @param optionVisible 底部菜单
     */
    private void showOrHideOption(int optionVisible) {
        mOptionIv.setVisibility(optionVisible);
    }

    private void cameraActivityStart() {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.setComponent(new ComponentName("com.umeox.watch.moto.camera", "com.umeox.watch.moto.camera.CameraActivity"));
        AlbumListActivity.this.startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            mPhotos.removeAll(mAlbumListAdapter.getPhotosSelected());
            mAlbumListAdapter.resetData();
            mHandler.sendEmptyMessage(DELETE_COMPLETE);
        }
    }
}
